﻿using System.IO;
using System.Text;
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using UnityEngine;

namespace CGF
{
    //监听打包过程
    public class BuildPreprocessListenner : IPreprocessBuildWithReport, IPostprocessBuildWithReport
    {
        public int callbackOrder { get { return 1; } }

        //构建之前调用
        public void OnPreprocessBuild(BuildReport report)
        {
            CGFConfig config = Resources.Load<CGFConfig>(typeof(CGFConfig).Name);
            config.isAppBundle = EditorUserBuildSettings.buildAppBundle;
            EditorUtility.SetDirty(config);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }

        //构建完成后调用
        public void OnPostprocessBuild(BuildReport report)
        {
            if (report.summary.platform == BuildTarget.WebGL)
            {
                string outputPath = report.summary.outputPath;
                string version = $"{CGFConfig.Instance.VersionName}.{CGFConfig.Instance.VersionCode}";

                string[][] fileList =
                {
                    new[] { "web.loader.js", $"web.loader.v{version}.js" },
                    new[] { "web.data.unityweb", $"web.data.v{version}.unityweb" },
                    new[] { "web.framework.js.unityweb", $"web.framework.js.v{version}.unityweb" },
                    new[] { "web.wasm.unityweb", $"web.wasm.v{version}.unityweb" },
                };
                //清除已经加过版本后缀的文件，保留刚导出的文件
                if (Directory.Exists($"{outputPath}/Build"))
                {
                    string[] files = Directory.GetFiles($"{outputPath}/Build");
                    foreach (string file in files)
                    {
                        try
                        {
                            string fileName = Path.GetFileName(file);
                            bool isValidFile = false;
                            for (int i = 0; i < fileList.Length; i++)
                            {
                                if (fileName == fileList[i][0])
                                {
                                    isValidFile = true;
                                    break;
                                }
                            }
                            if (isValidFile) continue;
                            File.Delete(file);
                            Debug.Log($"已删除文件: {file}");
                        }
                        catch (System.Exception e)
                        {
                            Debug.LogError(e.Message);
                        }
                    }
                }
                //修改文件名
                for (int i = 0; i < fileList.Length; i++)
                {
                    try
                    {
                        string[] files = fileList[i];
                        string fromPath = $"{outputPath}/Build/{files[0]}";
                        if (File.Exists(fromPath))
                        {
                            File.Move(fromPath, $"{outputPath}/Build/{files[1]}");
                        }
                    }
                    catch (System.Exception e)
                    {
                        Debug.LogError(e.Message);
                    }
                }
                //修改index.html的引用
                string indexPath = $"{outputPath}/index.html";
                string indexContent = File.ReadAllText(indexPath);
                for (int i = 0; i < fileList.Length; i++)
                {
                    string[] files = fileList[i];
                    indexContent = indexContent.Replace(files[0], files[1]);
                }
                File.WriteAllText(indexPath, indexContent, Encoding.UTF8);

                //修改ServiceWorker.js的引用
                string swPath = $"{outputPath}/ServiceWorker.js";
                if (File.Exists(swPath))
                {
                    string swContent = File.ReadAllText(swPath);
                    for (int i = 0; i < fileList.Length; i++)
                    {
                        string[] files = fileList[i];
                        swContent = swContent.Replace(files[0], files[1]);
                    }
                    File.WriteAllText(swPath, swContent, Encoding.UTF8);
                }
            }
        }
    }
}
